// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ionic-material', 'ion-affix', 'ngCordova', 'starter.controllers', 'starter.services', 'ionicServiceCore', 'ionicServiceDeploy', 'tabSlideBox', 'angular-timeline'])

    // 初始化全局变量设置
    .constant('Settings', {
        Context: {
            path: 'http://crmas.fangbaba.com/crmas',
            // path: 'http://crmas.fangbaba.cc/crmas',
            // path: 'http://192.168.0.17:8004/crmas',
            // path: 'http://211.157.155.194:8012/crmas',
            qiniuUpload: 'http://upload.qiniu.com/',
            // qiniuDownload: 'https://dn-imke.qbox.me/',
            qiniuDownload: 'https://dn-imke-pro.qbox.me/',
            qiniuUploadBroadcastKey: 'QINIU_UPLOAD_KEY'
        }
    })

    .run(function ($rootScope, $ionicPlatform, $ionicModal, $state, $ionicPopup, $ionicHistory, $cordovaToast, CrmHttp, Settings, $cordovaSplashscreen, $timeout, $cordovaActionSheet, $cordovaCamera, $cordovaImagePicker, $cordovaFileTransfer, versionUpdateService, $ionicLoading, $cordovaDevice, PasswordCheckService) {
        var currentPlatform = ionic.Platform.platform();
        $rootScope.devicInfo = {}; //设备信息
        $rootScope.appVersionInfo = {'binary': '0.0', 'deploy': '0'}; //应用版本信息
        $rootScope.passwordSafety = true; //密码安全性
        $rootScope.passwordSafetyChecked = false; //密码安全性检查

        $ionicPlatform.ready(function () {

            // 插件处理
            if (window.cordova) {

                // 键盘 Hide the accessory bar by default (remove this to show the accessory bar above the keyboard for form inputs)
                if (window.cordova.plugins.Keyboard) {
                    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
                    // cordova.plugins.Keyboard.disableScroll(true);

                    // get device devicInfo
                    $rootScope.devicInfo = $cordovaDevice.getDevice();
                }

                // 状态条
                if (window.StatusBar) {
                    // org.apache.cordova.statusbar required
                    StatusBar.styleDefault();
                }

                // 锁屏
                if (screen.lockOrientation) {
                    screen.lockOrientation('portrait');
                }

                // 版本更新升级 Version Upgrade
                versionUpdateService.init().then(
                    function () {
                        var version = versionUpdateService.getVersion();
                        $rootScope.appVersionInfo = version;
                        versionUpdateService.check(true); //强制更新
                    },
                    function (err) {
                        //
                    }
                );

                // 百度推送启用
                try {
                    pushPlugin.init(
                        function (res) {
                            //notify
                            if (res == 'ok') {
                                if (!$rootScope.hasMsg) {
                                    $rootScope.$apply(function () {
                                        $rootScope.hasMsg = true;
                                    });
                                }
                            } else {
                                console.log(res);
                            }
                        },
                        function (res) {
                            console.error("Push Serv Init failed");
                        }
                    );
                } catch (e) {
                    //
                }

                // 百度推送未启用
                var baiduApiKey = "";
                if (ionic.Platform.isIOS()) {
                    baiduApiKey = "Z47gBHQWo1yUaIz5RiojGUtV;"
                } else if (ionic.Platform.isAndroid()) {
                    baiduApiKey = "vmD7CAg5u57S4uHnN47XdB0b;"
                }
                try {
                    baidu_push && baidu_push.startWork(baiduApiKey, $rootScope.baiduPushCallback);
                } catch (e) {
                    //
                }

                // 高德定位 Position1.0 已禁用
                /**$rootScope.position = {
                    longitude: null,
                    latitude: null
                };
                 var _getPos = function () {
                    window.amapLocation && window.amapLocation.getCurrentPosition(function (res) {
                        var newLongitude = res.longitude;
                        var newLatitude = res.latitude;
                        if (res && newLongitude && newLatitude) {
                            $rootScope.position.longitude = newLongitude;
                            $rootScope.position.latitude = newLatitude;
                        }
                    }, function (err) {
                        //
                    });
                };
                 if (ionic.Platform.isIOS()) {
                    _getPos();
                    window.amapLocation && setInterval(function () {
                        //get Position
                        _getPos();
                    }, 60 * 1000);
                } else if (ionic.Platform.isAndroid()) {
                    window.amapLocation && window.amapLocation.start(function (res) {
                        _getPos();
                        window.amapLocation && setInterval(function () {
                            //get Position
                            _getPos();
                        }, 60 * 1000);
                    }, function (err) {
                    },{'interval':60});
                }*/
                    // 高德定位 Position2.0 已启用
                $rootScope.position = {
                    longitude: null,
                    latitude: null,
                    recentTrack: []
                };
                var GaodeSdkApiKey = "";
                var _setPos = function (res) {
                    var newLongitude = res.longitude;
                    var newLatitude = res.latitude;
                    if (res && newLongitude && newLatitude) {
                        $rootScope.position.longitude = newLongitude;
                        $rootScope.position.latitude = newLatitude;
                        if ($rootScope.position.recentTrack.length == 50) {
                            _.rest($rootScope.position.recentTrack).push({
                                "longitude": newLongitude,
                                "latitude": newLatitude
                            });
                        } else {
                            $rootScope.position.recentTrack.push({"longitude": newLongitude, "latitude": newLatitude});
                        }
                    }
                };
                try {
                    if (ionic.Platform.isIOS()) {
                        GaodeSdkApiKey = '32ed6c6be55960960f35066b194fd2f0';
                        AMapPlugin && AMapPlugin.configure(GaodeSdkApiKey, 100, function (res) { //位置变化范围（单位：米）
                            AMapPlugin && AMapPlugin.start(function (res) {
                                document.addEventListener("AMap.updateLocation", _setPos);
                            }, function (err) {
                                console.log("start error:" + err.errCode + " " + err.errInfo);
                            });
                        }, function (err) {
                            console.log("configure error:" + err);
                        });
                    } else if (ionic.Platform.isAndroid()) {
                        GaodeSdkApiKey = '1bd4f95a06cc7b20f171ff6cfaa4e6fd';
                        AMapPlugin && AMapPlugin.configure(GaodeSdkApiKey, '60000', function (res) { //时间变化范围（单位：毫秒）
                            AMapPlugin && AMapPlugin.start(function (res) {
                                if (res == "OK") {
                                    console.log("start init:" + res);
                                } else {
                                    _setPos(res);
                                }
                            }, function (err) {
                                console.log("start error:" + err.errCode + " " + err.errInfo);
                            });
                        }, function (err) {
                            console.log("configure error:" + err);
                        });
                    }
                } catch (e) {
                    console.log("AMapPlugin error:" + e);
                }

                // 启动友盟插件
                window.plugins.umengAnalyticsPlugin.init(function () {
                    console.log('========*******========> umeng init success');
                }, function (error) {
                    if (typeof error == 'string') {
                        console.log('========*******========> umeng error: ' + error);
                    } else {
                        console.log('========*******========> umeng error: ' + JSON.stringify(error));
                    }
                });

                // 友盟调试 debug
                /*window.plugins.umengAnalyticsPlugin.setDebugMode(true,function() {
                 console.log('========*******========> umeng init success');
                 } , function(error) {
                 if (typeof error == 'string') {
                 console.log('========*******========> umeng error: ' + error);
                 } else {
                 console.log('========*******========> umeng error: ' + JSON.stringify(error));
                 }
                 });*/

                // 启动屏
                if (currentPlatform == "android" && navigator.splashscreen) {
                    navigator.splashscreen.hide();
                }
            }

        });

        // 友盟组件调用
        $rootScope.umengEventObj = {
            /**
             * var event = {"eventId":"test" , "content":{"type":"type1" , "quantity":"3"}};
             * @param event 事件
             * @param content 内容
             * @param success 成功回调
             * @param error 错误回调
             */
            onEvent: function (event, success, error) {
                if (window.plugins && window.plugins.umengAnalyticsPlugin) {
                    window.plugins.umengAnalyticsPlugin.onEvent(event, success, error);
                } else {
                    if (error) {
                        error({'errorMsg': 'errorMsg========*******========> umeng组件不存在'});
                    }
                    console.log('========*******========> umeng组件不存在');
                }
            },
            /**
             * 根据eventId添加计数
             * @param eventId eventId
             */
            onEventById: function (eventId) {
                var event = {"eventId": eventId};
                this.onEvent(event, function (result) {
                    console.log('========*******========> umeng add event by id ok: ' + eventId);
                }, function (error) {
                    console.log('========*******========> umeng add event by id error : ' + eventId);
                });
            }

        };

        /**
         * 网络状态
         */
        $rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
            $cordovaToast.showLongBottom('网络已连接');
        });
        $rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
            $cordovaToast.showLongBottom('网络已断开');
        });

        //监听路由事件
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            // alert(toState.name + '---' + fromState.name + '---' + JSON.stringify(toParams));
            var stateName = toState.name;
            // 任务
            if (stateName == 'app.task') {
                $rootScope.umengEventObj.onEventById('home_work');
                // 公海
            } else if (stateName == 'app.hotel-list-public') {
                $rootScope.umengEventObj.onEventById('home_public');
                // 私海
            } else if (stateName == 'app.hotel-list-private') {
                // 首页点击私海标签
                if (toParams && !toParams.isHealthy) {
                    $rootScope.umengEventObj.onEventById('home_private');
                    // 健康
                } else if (toParams && toParams.isHealthy == 1) {
                    $rootScope.umengEventObj.onEventById('home_health');
                    // 一般
                } else if (toParams && toParams.isHealthy == 2) {
                    $rootScope.umengEventObj.onEventById('home_general');
                    // 危险
                } else if (toParams && toParams.isHealthy == 3) {
                    $rootScope.umengEventObj.onEventById('home_danger');
                }
                // 报表
            } else if (stateName == 'app.chars') {
                $rootScope.umengEventObj.onEventById('home_char');
                // 结算
            } else if (stateName == 'app.bills') {
                $rootScope.umengEventObj.onEventById('home_bill');
                // 酒店数
            } else if (stateName == 'app.hotel-list-myself') {
                $rootScope.umengEventObj.onEventById('home_hotelCount');
                // 余额
            } else if (stateName == 'app.my-bills') {
                $rootScope.umengEventObj.onEventById('home_balance');
                // 分销查询
            } else if (stateName == 'app.chars-distribution-order') {
                $rootScope.umengEventObj.onEventById('char_swath');
                // 采购查询
            } else if (stateName == 'app.chars-purchase') {
                $rootScope.umengEventObj.onEventById('char_purchase');
                // 洗涤查询
            } else if (stateName == 'app.chars-wash') {
                $rootScope.umengEventObj.onEventById('char_wash');
                // 拜访查询
            } else if (stateName == 'app.chars-visit') {
                $rootScope.umengEventObj.onEventById('char_wash');
            }
        });
        //未启用
        $rootScope.baiduPushCallback = function (json) {
            /**onbind,onunbind,onsettags,ondeltags,onlisttags,onmessage,onnotificationclicked,onnotificationarrived*/

            var eventType = json.type;
            var data = json.data;
            if (eventType == "onbind") { //绑定回调
                console.log("绑定成功");
            } else if (eventType == "onunbind") { //解除绑定回调
                console.log("解除绑定成功");
            } else if (eventType == "onsettags") { //TAG绑定回调

            } else if (eventType == "ondeltags") { //解除TAG绑定回调

            } else if (eventType == "onlisttags") { //LISTTAG绑定回调

            } else if (eventType == "onmessage") { //透传消息回调

            } else if (eventType == "onnotificationclicked") { //通知点击回调
                if (!$rootScope.hasMsg) {
                    $rootScope.hasMsg = true;
                }
            } else if (eventType == "onnotificationarrived") { //通知接收回调
                if (!$rootScope.hasMsg) {
                    $rootScope.hasMsg = true;
                }
            }
        };

        // modal队列
        $rootScope.modalQueueFramework = {
            queueList: [],
            setQueueList: function (key, modalHandle) {
                this.queueList.push({
                    key: key,
                    modalHandle: modalHandle
                })
            },
            removeQueue: function (key) {
                var that = this;
                var list = [];
                angular.forEach(that.queueList, function (queue) {
                    if (queue.key !== key) {
                        list.push(queue);
                    }
                });
                that.queueList = list;
            },
            removeQueueLast: function () {
                var that = this;
                var last = _.last(that.queueList);
                if (last && last.modalHandle) {
                    last.modalHandle.hide();
                }
                that.queueList = _.initial(that.queueList);
            },
            getQueueList: function () {
                return this.queueList;
            }
        };

        // Message Modal
        $ionicModal.fromTemplateUrl('templates/modal/msgList-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-down',
            hardwareBackButtonClose: true
        }).then(function (modal) {
            $rootScope.msgListModal = modal;
        });
        $rootScope.openMsgModal = function () {
            //$rootScope.msg.all();
            $rootScope.msgListModal.show();
            $rootScope.$broadcast("msg-list-open");
            //$rootScope.modalQueueFramework.setQueueList('msg', $rootScope.msgListModal);
        };
        $rootScope.closeMsgModal = function () {
            //$rootScope.msgListModal._deregisterBackButton && $rootScope.msgListModal._deregisterBackButton();
            $rootScope.msgListModal.hide();
            //$rootScope.modalQueueFramework.removeQueue('msg');
        };

        //双击退出
        var _backExit;

        function registBackExit(priority) {
            _backExit && _backExit();
            _backExit = $ionicPlatform.registerBackButtonAction(function (e) {
                //判断处于哪个页面时双击退出
                if ($state.current.name == 'app.main' || !$rootScope.localStorageObj.userId) {
                    if ($rootScope.backButtonPressedOnceToExit) {
                        ionic.Platform.exitApp();
                    } else {
                        $rootScope.backButtonPressedOnceToExit = true;
                        $cordovaToast.showShortBottom('再按一次退出系统');
                        setTimeout(function () {
                            $rootScope.backButtonPressedOnceToExit = false;
                        }, 2000);
                    }
                    //e.preventDefault();
                    //return false;
                }
                else {
                    $ionicHistory.goBack();
                }
            }, priority);
        };
        registBackExit(101);
        var viewEnterFlag = false;

        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            // 密码检查
            if (!$rootScope.passwordSafety) {
                PasswordCheckService.popupPasswordWarning();
                event.preventDefault();
                return;
            }
            //if (!$rootScope.passwordSafetyChecked) {
            //    PasswordCheckService.checkPasswordSecurity();
            //}

            // 版本检查
            if (window.cordova && $rootScope.updateAppStore) {
                event.preventDefault();
                versionUpdateService.updatePackage(); //强制更新大版本
                return;
            }
            if (window.cordova && !versionUpdateService.checkSuccess() && versionUpdateService.getVersion()) {
                event.preventDefault();
                versionUpdateService.check(true); //强制检查更新
                return;
            }

            if (viewEnterFlag) {
                event.preventDefault();
            } else {
                viewEnterFlag = true;
            }
        });
        $rootScope.$on('$ionicView.afterEnter', function () {
            viewEnterFlag = false;
        });

        //根路径
        $rootScope.contextPath = Settings.Context.path;
        $rootScope.Settings = Settings;

        var callback = function (buttonIndex, telList) {
            setTimeout(function () {
                // like other Cordova plugins (prompt, confirm) the buttonIndex is 1-based (first button is index 1)
                // alert(telList + 'button index clicked: ' + buttonIndex);
                location.href = 'tel:' + telList[btnIndex - 1];
            });
        };

        // 显示酒店电话列表
        $rootScope.showTelList = function (event, telList) {
            var options = {
                title: '电话列表',
                buttonLabels: telList,
                addCancelButtonWithLabel: '取消',
                androidEnableCancelButton: true,
                winphoneEnableCancelButton: true
                // addDestructiveButtonWithLabel : 'Delete it'
            };
            $cordovaActionSheet.show(options).then(function (btnIndex) {
                // 取消按钮
                if (telList.length + 1 > btnIndex) {
                    location.href = 'tel:' + telList[btnIndex - 1];
                }
            });

            /* var options = {
             'title': '电话列表',
             //'buttonLabels': ['13301360605', '13301360605'],
             //'buttonLabels': telList,
             'androidEnableCancelButton' : true,
             'winphoneEnableCancelButton' : true,
             'addCancelButtonWithLabel': '取消'
             };
             window.plugins.actionsheet.show(options, callback(telList));*/
            event.stopPropagation();
        };

        // 上传图片
        $rootScope.chooseUploadType = function () {
            var options = {
                title: '上传照片',
                buttonLabels: ['拍照', '相册选择'],
                addCancelButtonWithLabel: '取消',
                androidEnableCancelButton: true,
                winphoneEnableCancelButton: true
            };
            $cordovaActionSheet.show(options).then(function (btnIndex) {
                ImageGallery.uploadImage($rootScope, $ionicLoading, $cordovaCamera, $cordovaImagePicker, $cordovaFileTransfer, Settings, btnIndex);
            });
        };

        // 登录对象
        $rootScope.login = {
            loginname: null,
            password: null,
            hxname: null,
            hxpassword: null
        };

        // 用户对象
        $rootScope.localStorageObj = Login.getLoginInfo();

        // 登录modal
        $ionicModal.fromTemplateUrl('templates/modal/login-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-up',
            hardwareBackButtonClose: false
        }).then(function (modal) {
            $rootScope.modal = modal;
        });
        $rootScope.openLoginModal = function () {
            $rootScope.modal.show();
        };
        $rootScope.closeModal = function () {
            $rootScope.modal._deregisterBackButton && $rootScope.modal._deregisterBackButton(); //解决android modal背杀掉返回键不好用的bug
            $rootScope.modal.hide();
        };
        // Execute action on remove modal
        $rootScope.$on('modal.shown', function () {
            registBackExit(201);
        });
        // Execute action on hide modal
        $rootScope.$on('modal.hidden', function () {
            registBackExit(101);
        });

        // 图片画廊modal
        $ionicModal.fromTemplateUrl('templates/modal/image-gallery-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-up',
            hardwareBackButtonClose: false
        }).then(function (modal) {
            $rootScope.galleryModal = modal;
        });
        $rootScope.openGalleryModal = function () {
            $rootScope.galleryModal.show();
            $rootScope.modalQueueFramework.setQueueList('gallery', $rootScope.galleryModal);
        };
        $rootScope.closeGalleryModal = function () {
            $rootScope.gallerySelectFlag = false;
            $rootScope.galleryModal._deregisterBackButton && $rootScope.galleryModal._deregisterBackButton(); //解决android modal背杀掉返回键不好用的bug
            $rootScope.galleryModal.hide();
            ImageGallery.hide();
            $rootScope.modalQueueFramework.removeQueue('gallery');
        };

        // 图片view modal
        $ionicModal.fromTemplateUrl('templates/modal/image-browser-view-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-up',
            hardwareBackButtonClose: false
        }).then(function (modal) {
            $rootScope.galleryViewModal = modal;
        });
        $rootScope.openGalleryViewModal = function () {
            $rootScope.galleryViewModal.show();
            $rootScope.modalQueueFramework.setQueueList('gallery-view', $rootScope.galleryViewModal);
        };
        $rootScope.closeGalleryViewModal = function () {
            $rootScope.galleryViewModal._deregisterBackButton && $rootScope.galleryViewModal._deregisterBackButton(); //解决android modal背杀掉返回键不好用的bug
            $rootScope.galleryViewModal.hide();
            $rootScope.modalQueueFramework.removeQueue('gallery-view');
        };

        // 选择删除图片
        $rootScope.selectGallery = function () {
            $rootScope.gallerySelectFlag = $rootScope.gallerySelectFlag === true ? false : true;
        },

            // 删除图片
            $rootScope.deleteGallery = function () {
                var list = [];
                var hasActive = false;
                angular.forEach($rootScope.galleryItems, function (item) {
                    if (!item.active) {
                        list.push(item);
                    } else {
                        hasActive = true;
                    }
                });
                if (!hasActive) {
                    $cordovaToast.showShortBottom('请选择要删除的图片');
                } else {
                    $rootScope.galleryItems = list;
                    ImageGallery.resetGalleryList();
                    $rootScope.gallerySelectFlag = false;
                }
            };

        // 图片浏览modal
        $ionicModal.fromTemplateUrl('templates/modal/image-browser-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-up',
            hardwareBackButtonClose: false
        }).then(function (modal) {
            $rootScope.browserModal = modal;
        });

        // 打开浏览图片
        $rootScope.openBrowserModal = function (browserPhotoList, index, readOnly) {
            var _pushItem = function (item) {
                var _itemVal = function (url) {
                    if (url.length > 1) {
                        $rootScope.browserPhotoList.push(url[0]);
                    } else {
                        $rootScope.browserPhotoList.push(url.join(''));
                    }
                }
                if (item.src) {
                    var photoUrl = item.src.split('?');
                    _itemVal(photoUrl);
                } else if (item.url) {
                    var photoUrl = item.url.split('?');
                    _itemVal(photoUrl);
                } else {
                    $rootScope.browserPhotoList.push(item);
                }
            };
            // 选择删除对象
            if ($rootScope.gallerySelectFlag) {
                for (var i = 0; i < $rootScope.galleryItems.length; i++) {
                    var item = $rootScope.galleryItems[i];
                    if (i === index) {
                        if (!item.active) {
                            item.active = true;
                        } else {
                            item.active = false;
                        }
                    }
                }
            } else {
                $rootScope.browserPhotoActiveSlide = index;
                $rootScope.browserPhotoList = [];
                if (typeof browserPhotoList === 'string') {
                    if (browserPhotoList) {
                        var photoUrl = browserPhotoList.split('?');
                        if (photoUrl.length > 1) {
                            $rootScope.browserPhotoList.push(photoUrl[0]);
                        } else {
                            $rootScope.browserPhotoList.push(photoUrl.join(''));
                        }
                    }
                } else {
                    if (browserPhotoList && browserPhotoList.length > 0) {
                        if (readOnly === true) {
                            for (var i = 0; i < browserPhotoList.length; i++) {
                                var item = browserPhotoList[i];
                                _pushItem(item);
                            }
                        } else {
                            for (var i = 0; i < browserPhotoList.length - 1; i++) {
                                var item = browserPhotoList[i];
                                _pushItem(item);
                            }
                        }
                    }// else {
                    // $cordovaToast.showShortBottom('无图片可预览');
                    // $rootScope.browserPhotoList.push(browserPhotoList.src.script('?')[0]);
                    //}
                }
                $timeout(function () {
                    if (readOnly === true) {
                        if ($rootScope.browserPhotoList.length > 0) {
                            $rootScope.galleryReadOnlyFlag = true;
                            $rootScope.openGalleryViewModal();
                        } else {
                            $cordovaToast.showShortBottom('无图片可预览');
                        }
                    } else {
                        $rootScope.browserModal.show();
                        $rootScope.modalQueueFramework.setQueueList('browser', $rootScope.browserModal);
                    }
                }, 0);
            }
        };

        // 关闭图片浏览
        $rootScope.closeBrowserModal = function () {
            if ($rootScope.galleryReadOnlyFlag) {
                $rootScope.galleryReadOnlyFlag = false;
                $rootScope.closeGalleryViewModal();
            } else {
                $rootScope.browserModal._deregisterBackButton && $rootScope.browserModal._deregisterBackButton();
                $rootScope.browserModal.hide();
                $rootScope.modalQueueFramework.removeQueue('browser');
            }
        };

        // 忘记密码modal
        $ionicModal.fromTemplateUrl('templates/modal/login-forget-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-left',
            hardwareBackButtonClose: false
        }).then(function (modal) {
            $rootScope.loginForgetModal = modal;
        });
        $rootScope.openLoginForgetModal = function (title, isHideLogin) {
            if (isHideLogin === true) {
                $rootScope.loginForgetModal.loginBtnHide = true;
            } else {
                $rootScope.loginForgetModal.loginBtnHide = false;
            }
            if (title) {
                $rootScope.forgetPassword.reset();
            }
            $rootScope.loginForgetModal.title = title;
            $rootScope.loginForgetModal.show();
            $rootScope.modalQueueFramework.setQueueList('login-forget', $rootScope.loginForgetModal);
        };
        $rootScope.closeLoginForgetModal = function () {
            $rootScope.loginForgetModal._deregisterBackButton && $rootScope.loginForgetModal._deregisterBackButton(); //解决android modal背杀掉返回键不好用的bug
            $rootScope.loginForgetModal.hide();
            $rootScope.modalQueueFramework.removeQueue('login-forget');
        };

        // 发送验证码校验modal
        $ionicModal.fromTemplateUrl('templates/modal/login-checkcode-modal.html', {
            scope: $rootScope,
            animation: 'slide-in-left',
            hardwareBackButtonClose: false
        }).then(function (modal) {
            $rootScope.loginCheckCodeModal = modal;
        });
        $rootScope.openLoginCheckCodeModal = function () {
            $rootScope.loginCheckCodeModal.show();
            $rootScope.modalQueueFramework.setQueueList('login-check-code', $rootScope.loginCheckCodeModal);
        };
        $rootScope.closeLoginCheckCodeModal = function () {
            $rootScope.loginCheckCodeModal._deregisterBackButton && $rootScope.loginCheckCodeModal._deregisterBackButton(); //解决android modal背杀掉返回键不好用的bug
            $rootScope.loginCheckCodeModal.hide();
            $rootScope.modalQueueFramework.removeQueue('login-check-code');
        };

        // 显示登录modal
        $rootScope.showLoginModal = function () {
            $rootScope.closeLoginForgetModal();
            $rootScope.closeLoginCheckCodeModal();
        };

        //忘记密码交互方法
        $rootScope.forgetPassword = {
            showCodeBtn: true,
            timer: 119,
            code: '',
            newPassword: '',
            conformPassword: '',
            identifiedKey: '',
            reset: function(){
                this.code = '';
            },
            sendCode4Phone: function () {
                var that = this;
                if (!Tools.isMobileNo($rootScope.login.loginname)) {
                    $cordovaToast.showLongBottom('手机号码输入不合法');
                    return;
                }
                CrmHttp.post('/crm/sms/resetPwdverifyCode', {
                    phoneNum: $rootScope.login.loginname,
                    isLogin: true
                }).then(function (resultData) {
                    var data = resultData.data;
                    if (data.success) {
                        that.showCodeBtn = false;
                        that.showTimer();
                    } else {
                        $cordovaToast.showLongBottom(data.errorMsg);
                    }
                }, function (error) {
                    $cordovaToast.showLongBottom('验证码获取失败');
                });
            },
            showTimer: function () {
                var that = this;
                $timeout(function () {
                    if (that.timer > 0) {
                        that.timer--;
                        that.showTimer();
                    } else {
                        that.timer = 119;
                        that.showCodeBtn = true;
                    }
                }, 1000);
            },
            next: function () {
                var that = this;
                if (!that.code) {
                    $cordovaToast.showLongBottom('请输入验证码');
                    return;
                }
                CrmHttp.post('/crm/sms/verifyCodeNext', {
                    phoneNum: $rootScope.login.loginname,
                    verifyCode: that.code,
                    isLogin: true
                }).then(function (resultData) {
                    var data = resultData.data;
                    if (data.success) {
                        $rootScope.closeLoginForgetModal();
                        $rootScope.openLoginCheckCodeModal();
                        that.identifiedKey = data.attribute.key || '';
                    } else {
                        $cordovaToast.showLongBottom(data.errorMsg);
                    }
                }, function (error) {
                    $cordovaToast.showLongBottom(error.errorMsg);
                });
            },
            backForget: function () {
                $rootScope.openLoginForgetModal();
                $rootScope.closeLoginCheckCodeModal();
            },
            submit: function () {
                var that = this;
                if (that.newPassword == that.conformPassword) {
                    CrmHttp.post('/crm/app/reset-pwd', {
                        newPass: that.conformPassword,
                        timestamp: new Date(),
                        isLogin: true,
                        key: that.identifiedKey
                    }).then(function (resultData) {
                        var data = resultData.data;
                        if (data.success) {
                            if ($rootScope.localStorageObj && $rootScope.localStorageObj.userId) {
                                $rootScope.closeLoginCheckCodeModal();
                                $rootScope.signOutWithoutConfirm();
                            } else {
                                $cordovaToast.showLongBottom('密码修改成功,点击右上角 [登录] 返回登录页面');
                            }
                            $rootScope.passwordSafety = true;
                        } else {
                            $cordovaToast.showLongBottom(data.errorMsg);
                        }
                    }, function (error) {
                        $cordovaToast.showLongBottom(error.errorMsg);
                    });
                } else {
                    $cordovaToast.showLongBottom('两次密码输入不一致');
                }
            }
        };

        //Cleanup the modal when we're done with it!
        $rootScope.$on('$destroy', function () {
            $rootScope.modal.remove();
            $rootScope.galleryModal.remove();
            $rootScope.browserModal.remove();
            $rootScope.loginForgetModal.remove();
            $rootScope.loginCheckCodeModal.remove();
        });
        // 退出
        $rootScope.signOut = function () {
            var confirmPopup = $ionicPopup.confirm({
                title: '退出',
                template: '您确认退出系统吗？',
                cancelText: '取消',
                cancelType: 'button-block button-outline button-energized-crm',
                okText: '确定',
                okType: 'button-block button-energized-crm',
            });

            confirmPopup.then(function (res) {
                if (res) {
                    $rootScope.signOutWithoutConfirm();
                }
            });
        };

        // 强行退出
        $rootScope.signOutWithoutConfirm = function () {
            $rootScope.login = {
                loginname: null,
                password: null,
                hxname: null,
                hxpassword: null
            };
            Login.setLoginInfo(null);
            $rootScope.$broadcast('LOGIN_OUT', {});
            $rootScope.openLoginModal();
        };

        // 登录方法
        function loginFunc(loginname, password) {

            var _login;
            var params = {
                loginname: loginname,
                password: password,
                isLogin: true,
                devicInfo: JSON.stringify($rootScope.devicInfo)
            };

            _login = function (params) {
                $ionicLoading.show({
                    template: '正在登录...',
                    animation: 'fade-in',
                    showBackdrop: true,
                    duration: 5000,
                    showDelay: 0
                });
                CrmHttp.post('/crm/app/login', params).then(function (result) {
                    var resData = result.data;
                    if (resData.success) {
                        $rootScope.localStorageObj = resData.attribute;
                        $rootScope.localStorageObj.loginname = params.loginname;
                        $rootScope.localStorageObj.password = params.password;
                        Login.setLoginInfo($rootScope.localStorageObj);
                        $rootScope.$broadcast('LOGIN', $rootScope.localStorageObj);
                        $rootScope.closeModal();
                        // 建立服务器间连接
                        CrmHttp.post('/crm/validate', {ticket: resData.attribute.st, service: Settings.Context.path});
                        // 检查是否需要修改密码
                        if (resData.attribute.isDefaultPwd  && resData.attribute.isDefaultPwd == '0') {
                            $rootScope.passwordSafety = false;
                            PasswordCheckService.popupPasswordWarning();
                        } else {
                            $rootScope.passwordSafety = true;
                        }
                    } else {
                        window.cordova && $cordovaToast.showShortBottom('用户登录失败,错误信息:' + resData.errorMsg);
                    }
                    $ionicLoading.hide();
                    isLoading = false;
                }, function (error) {
                    window.cordova && $cordovaToast.showShortBottom('用户登录失败');
                    $ionicLoading.hide();
                    isLoading = false;
                });
            };

            //Push Serv Start
            if (window.cordova) {
                try {
                    pushPlugin.startWork(
                        function (res) {
                            if (res == "error") {
                                console.log("Push Start Work error");
                                _login(params);
                                return;
                            }
                            params.loginDevic = ionic.Platform.platform();
                            params.channelId = res;
                            _login(params);
                        },
                        function (res) {
                            console.error("Push Start Work failed");
                            _login(params);
                        }
                    );
                } catch (e) {
                    _login(params);
                }
            } else {
                _login(params);
            }
        };

        // 自动登录操作
        $rootScope.autoLoginFunc = function () {
            var loginInfo = Login.getLoginInfo();
            if (!loginInfo || !loginInfo.token) {
                $rootScope.openLoginModal();
                return;
            }
            loginFunc(loginInfo.loginname, loginInfo.password);
        };

        // 设置登录用户信息
        var isLoading = false;
        $rootScope.setLoginInfo = function () {
            if (1 == 2 && !Tools.isMobileNo($rootScope.login.loginname)) {
                $cordovaToast.showShortBottom('用户名不合法, 请输入手机号');
            } else {
                if (isLoading) {
                    return;
                }
                isLoading = true;
                loginFunc($rootScope.login.loginname, $rootScope.login.password);
            }
        };

        //检查更新
        $rootScope.checkUpdate = function () {
            if (!window.cordova) {
                $ionicLoading.show({
                    template: '插件安装异常!',
                    animation: 'fade-in',
                    showBackdrop: true,
                    duration: 2000,
                    showDelay: 0
                });
            } else {
                versionUpdateService.checkUpdate(false);
            }
        };

    })

    .config(function ($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider, $compileProvider, $ionicAppProvider) {

        var currentPlatform = ionic.Platform.platform();

        $ionicConfigProvider.tabs.position('bottom');
        $ionicConfigProvider.tabs.style('standard');
        $ionicConfigProvider.navBar.alignTitle('center');

        $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):|data:image\//);

        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/app/main');

        // Ionic uses AngularUI Router which uses the concept of states
        // Learn more here: https://github.com/angular-ui/ui-router
        // Set up the various states which the app can be in.
        // Each state's controller can be found in controllers.js
        $stateProvider

        // setup an abstract state for the tabs directive
            .state('app', {
                url: '/app',
                abstract: true,
                templateUrl: 'templates/menu.html'
            })

            // Each tab has its own nav history stack:

            .state('app.main', {
                url: '/main',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-main.html',
                        controller: 'MainCtrl'
                    }
                }
            })

            .state('app.hotels', {
                url: '/hotels',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-hotels.html',
                        controller: 'HotelsCtrl'
                    }
                }
            })

            .state('app.hotels-list', {
                url: '/hotels/list/:type',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-hotels-list.html',
                        controller: 'HotelsListCtrl'
                    }
                }
            })

            .state('app.hotel-list-public', {
                url: '/hotels/list/public',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-list-public.html',
                        controller: 'HotelListPublicCtrl'
                    }
                }
            })
            .state('app.hotel-list-private', {
                url: '/hotels/list/private/{isHealthy}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-list-private.html',
                        controller: 'HotelListPrivateCtrl'
                    }
                }
            })
            .state('app.hotel-list-myself', {
                url: '/hotels/list/myself',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-list-private.html',
                        controller: 'HotelListPrivateCtrl'
                    }
                }
            })
            .state('app.hotel-list-filter', {
                url: '/hotels/list/filter/:type',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-list-filter.html',
                        controller: 'HotelListFilterCtrl'
                    }
                }
            })

            .state('app.hotel-main', {
                url: '/hotels/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-main.html',
                        controller: 'HotelMainCtrl'
                    }
                }
            })
            .state('app.hotel-rank', {
                url: '/hotels/hotel-rank/',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-rank-list.html',
                        controller: 'HotelRankListCtrl'
                    }
                }
            })
            .state('app.hotel-rank-detail', {
                url: '/hotels/hotel-rank-detail/{id}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-rank-detail.html',
                        controller: 'HotelRankDetailCtrl'
                    }
                }
            })
            .state('app.hotel-rank-edit', {
                url: '/hotels/hotel-rank-edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-rank-edit.html',
                        controller: 'HotelRankEditCtrl'
                    }
                }
            })
            .state('app.hotel-visit-edit', {
                url: '/hotels/hotel-visit-edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-visit-edit.html',
                        controller: 'HotelVisitEditCtrl'
                    }
                }
            })
            .state('app.hotel-baseinfo', {
                url: '/hotels/hotel-baseinfo/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-baseinfo.html',
                        controller: 'HotelBaseInfoCtrl'
                    }
                }
            })
            .state('app.hotel-baseinfo-edit', {
                url: '/hotels/hotel-baseinfo-edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-baseinfo-edit.html',
                        controller: 'HotelBaseInfoEditCtrl'
                    }
                }
            })
            .state('app.hotel-location', {
                url: '/hotels/hotel-location/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-location.html',
                        controller: 'HotelLocationCtrl'
                    }
                }
            })
            .state('app.hotel-location-edit', {
                url: '/hotels/hotel-location-edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-location-edit.html',
                        controller: 'HotelLocationEditCtrl'
                    }
                }
            })
            .state('app.hotel-facility', {
                url: '/hotels/hotel-facility/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-facility.html',
                        controller: 'HotelFacilityCtrl'
                    }
                }
            })
            .state('app.hotel-room-list', {
                url: '/hotels/hotel-room-list/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-room-list.html',
                        controller: 'HotelRoomTypeListCtrl'
                    }
                }
            })
            .state('app.hotel-room-info', {
                url: '/hotels/hotel-room-info/{roomTypeId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-room-info.html',
                        controller: 'HotelRoomTypeDetailCtrl'
                    }
                }
            })
            .state('app.hotel-room-info-edit', {
                url: '/hotels/hotel-room-info-edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-room-info-edit.html',
                        controller: 'HotelRoomInfoEditCtrl'
                    }
                }
            })
            .state('app.hotel-contact', {
                url: '/hotels/hotel-contact/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-contact.html',
                        controller: 'HotelContactCtrl'
                    }
                }
            })
            .state('app.hotel-contact-edit', {
                url: '/hotels/hotel-contact-edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-contact-edit.html',
                        controller: 'HotelContactEditCtrl'
                    }
                }
            })
            .state('app.hotel-activation', {
                url: '/hotels/hotel-activation/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-activation.html',
                        controller: 'HotelActivationCtrl'
                    }
                }
            })

            .state('app.work', {
                url: '/work',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-work.html',
                        controller: 'WorkCtrl'
                    }
                }
            })
            .state('app.task', {
                url: '/task',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/task/side-work.html',
                        controller: 'WorkCtrl'
                    }
                }
            })
            .state('app.task-detail', {
                url: '/task/detail/{id}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/task/side-work-detail.html',
                        controller: 'WorkDetailCtrl'
                    }
                }
            })
            .state('app.mine', {
                url: '/mine',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-mine.html',
                        controller: 'MineCtrl'
                    }
                }
            })

            .state('app.setting', {
                url: '/setting',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-setting.html',
                        controller: 'SettingCtrl'
                    }
                }
            })

            .state('app.about', {
                url: '/about',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-about.html',
                        controller: 'AboutCtrl'
                    }
                }
            })

            .state('app.about-memo', {
                url: '/about/memo',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-about-memo.html'
                    }
                }
            })

            .state('app.opinion', {
                url: '/opinion',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-opinion.html',
                        controller: 'OpinionCtrl'
                    }
                }
            })

            .state('app.bills', {
                url: '/bills',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-bills.html',
                        controller: 'BillsCtrl'
                    }
                }
            })
            .state('app.my-bills', {
                url: '/my-bills',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-bills.html',
                        controller: 'BillsCtrl'
                    }
                }
            })
            .state('app.bill-detail', {
                url: '/bill/detail/:billId',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-bill-detail.html',
                        controller: 'BillDetailCtrl'
                    }
                }
            })
            .state('app.support', {
                url: '/support',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-support.html',
                        controller: 'SupportCtrl'
                    }
                }
            })

            .state('app.support-contact', {
                url: '/support/contact',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/support-contact-list.html',
                        controller: 'ContactListCtrl'
                    }
                }
            })
            .state('app.hotel-activation-code', {
                url: '/support/hotel-activation-code',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-activation-code-list.html',
                        controller: 'HotelActivationCodeListCtrl'
                    }
                }
            })
            .state('app.hotel-activation-code-detail', {
                url: '/support/hotel-activation-code-detail',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-activation-code-detail.html',
                        controller: 'HotelActivationCodeDetailCtrl'
                    }
                }
            })
            .state('app.support-contact-hotel', {
                url: '/support/contact/hotel/{{hotelId}}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/support-contact-list.html',
                        controller: 'ContactListCtrl'
                    }
                }
            })
            .state('app.chars', {
                url: '/chars',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/side-chars.html',
                        controller: 'CharsCtrl'
                    }
                }
            })

            .state('app.chars-visit', {
                url: '/chars/visit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-visit.html',
                        controller: 'VisitCtrl'
                    }
                }
            })
            .state('app.hotel-visit-detail', {
                url: '/chars/visit/:id',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-visit-detail.html',
                        controller: 'HotelVisitDetailCtrl'
                    }
                }
            })
            .state('app.chars-visit-detail', {
                url: '/chars/visit/:id',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-visit-detail.html',
                        controller: 'VisitDetailCtrl'
                    }
                }
            })

            .state('app.chars-distribution', {
                url: '/chars/distribution',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-distribution.html',
                        controller: 'DistributionCtrl'
                    }
                }
            })

            .state('app.chars-distribution-detail', {
                url: '/chars/distribution/:id',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-distribution-detail.html',
                        controller: 'DistributionDetailCtrl'
                    }
                }
            })
            .state('app.chars-distribution-order', {
                url: '/chars/distribution-order',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-distribution-order.html',
                        controller: 'DistributionOrderCtrl'
                    }
                }
            })
            .state('app.chars-distribution-order-detail', {
                url: '/chars/distribution-order-detail/:orderId',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-distribution-order-detail.html',
                        controller: 'DistributionOrderDetailCtrl'
                    }
                }
            })
            .state('app.chars-purchase', {
                url: '/chars/purchase',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-purchase.html',
                        controller: 'PurchaseCtrl'
                    }
                }
            })
            .state('app.chars-purchase-detail', {
                url: '/chars/purchase-detail/:orderId',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-purchase-detail.html',
                        controller: 'PurchaseDetailCtrl'
                    }
                }
            })
            .state('app.chars-wash', {
                url: '/chars/wash',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-wash.html',
                        controller: 'WashCtrl'
                    }
                }
            })
            .state('app.chars-wash-detail', {
                url: '/chars/wash-detail/:orderId',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/chars-wash-detail.html',
                        controller: 'WashDetailCtrl'
                    }
                }
            })
            .state('app.hotel-price-analysis', {
                url: '/hotels/hotel-price-analysis/{hotelId}',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/hotel-price-analysis.html',
                        controller: 'HotelPriceAnalysisCtrl'
                    }
                }
            });

        // 使angular $http post提交和jQuery一致
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function (data) {
            /**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             */
            var param = function (obj) {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;

                for (name in obj) {
                    value = obj[name];

                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value !== undefined && value !== null) {
                        query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                    }
                }

                return query.length ? query.substr(0, query.length - 1) : query;
            };

            return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
        }];

        //更新设置
        $ionicAppProvider.identify({
            //这个应用的标识
            app_id: 'lezhu-crm',
            //生产环境的域名
            // domain: currentPlatform == "ios" ? 'http://crmas.fangbaba.cc/crmas/crm/ver' : 'http://crmas.fangbaba.cc/crmas/crm/ver',
            domain: currentPlatform == "ios" ? 'https://crmas.fangbaba.com/crmas/crm/ver' : 'http://crmas.fangbaba.com/crmas/crm/ver',
            // domain: currentPlatform == "ios" ? 'http://192.168.0.17:8004/crmas/crm/ver' : 'http://192.168.0.17:8004/crmas/crm/ver',
            //生产环境
            channel_tag: 'product'
        });

        // 画廊设置
        //ionGalleryConfigProvider.setGalleryConfig({
        //  action_label: 'Close',
        //  toggle: false,
        //  row_size: 3,
        //  fixed_row_size: true
        //});

    })
    .directive('errSrc', function () {
        return {
            link: function (scope, element, attrs) {
                element.bind('error', function () {
                    if (attrs.src != attrs.errSrc) {
                        attrs.$set('src', attrs.errSrc);
                    }
                });
            }
        }
    });